<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>注册页面</title>
    <link rel="stylesheet" href="../lib/layui/css/layui.css" />
    <link rel="stylesheet" href="../css/base.css" />
    <link rel="stylesheet" href="../css/form.css" />
  </head>

  <body>
    <div class="header container">注册页面</div>
    <form>
      <span class="error">用户名已存在，请更换！</span>
      <label>
        用户名：&nbsp;&nbsp;
        <input type="text" name="username" class="username" />
      </label>
      <label>
        密&nbsp;&nbsp;&nbsp;码： &nbsp;&nbsp;<input
          type="text"
          name="password"
          class="password"
        />
      </label>
      <label>
        确认密码： &nbsp;&nbsp;<input
          type="text"
          name="rpassword"
          class="rpassword"
        />
      </label>
      <label>
        昵&nbsp;&nbsp;&nbsp;称：&nbsp;&nbsp;
        <input type="text" name="nickname" class="nickname" />
      </label>
      <p>已有账号，<a href="./login.html">直接登录</a></p>
      <button type="submit">注册</button>
    </form>
    <script src="../lib/jquery.js"></script>
    <script src="../lib/axios.js"></script>
    <script>
      $(function () {
        $("form").on("submit", function (event) {
          event.preventDefault();
          var username = $(".username").val();
          var password = $(".password").val();
          var rpassword = $(".rpassword").val();
          var nickname = $(".nickname").val();

          if (!username || !password || !rpassword || !nickname) {
            alert("请填写所有必填项");
            return false;
          }

          if (password !== rpassword) {
            alert("两次密码不一致");
            return false;
          }
          axios
            .post("http://localhost:9000/users/register", {
              username: username,
              password: password,
              rpassword: rpassword,
              nickname: nickname,
            })
            .then(function (response) {
              if (response.data.code === 1) {
                alert(response.data.message);
                window.location.href = "./login.html";
              } else {
                alert(response.data.message);
              }
            })
            .catch(function (error) {
              alert("请求出错");
            });
        });
      });
    </script>
  </body>
</html>
